package cn.wolfcode.web.interceptor;

import cn.wolfcode.exception.CodeMsg;
import cn.wolfcode.redis.RedisKey;
import cn.wolfcode.util.Constants;
import cn.wolfcode.web.anno.RequireLogin;
import cn.wolfcode.web.result.Result;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by wolfcode-lanxw
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod) handler;
            if(!hm.hasMethodAnnotation(RequireLogin.class)){
                return true;
            }
            String token = request.getHeader(Constants.TOKEN_NAME);
            String key = RedisKey.USER_TOKEN_STRING.getRealKey(token);
            if (redisTemplate.hasKey(key)) {
                threadPoolTaskExecutor.execute(()->{
                    redisTemplate.expire(key,RedisKey.USER_TOKEN_STRING.getExpireTime(),RedisKey.USER_TOKEN_STRING.getUnit());
                });
                return true;
            }
            Result result = Result.error(CodeMsg.LOGIN_EXPIRED_ERROR);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }
        return true;
    }
}
